package com.fowo.api.service.handleWork;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.entity.*;
import com.fowo.api.model.purchase.plans.PurchasePlansVo;
import com.fowo.api.model.purchase.plans.product.PurchasePlansProductItemVo;
import com.fowo.api.model.purchase.plans.product.PurchasePlansProductVo;
import com.fowo.api.model.stock.in.StockInVo;
import com.fowo.api.model.stock.in.product.StockInProductItemVo;
import com.fowo.api.service.ListingFatherService;
import com.fowo.api.service.PurchasePlansProductService;
import com.fowo.api.service.PurchasePlansService;
import com.fowo.api.service.handleWork.jindieEntity.*;
import com.fowo.api.service.impl.*;
import com.fowo.api.sys.entity.SysUser;
import com.fowo.api.sys.service.SysUserService;
import com.fowo.api.sys.service.impl.SysUserServiceImpl;
import com.fowo.api.util.LocalDateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class SyncPurchasePlans {
    public  final static String path2="https://openapi.lingxing.com";
    public  final static String appId="ak_s4t9uVnYKwknd";
    public  final static String appSecret="xZHRMyjrRAfJkvVCoVWcxQ==";
    @Resource
    private PurchasePlansServiceImpl purchasePlansService;
    @Resource
    protected PurchasePlansProductServiceImpl purchasePlansProductService;
    @Resource
    private ProductServiceImpl service;
    @Resource
    private SupplierServiceImpl supplierServiceImpl;
    @Resource
    private WarehouseServiceImpl warehouseService;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private ListingFatherServiceImpl listingFatherService;
    @Resource
    private SysUserServiceImpl userService;
    @Resource
    private PurchaseOrderServiceImpl purchaseOrderService;

    @Transactional
    public void run() throws Exception {
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("appId",appId);
        queryParam.put("appSecret",appSecret);
        String url=path2+"/api/auth-server/oauth/access-token";
        RestTemplate REST_TEMPLATE = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>("", headers);
        String s= populateQueryParams(queryParam, url,false);
        ResponseEntity<Object> objectResponseEntity = REST_TEMPLATE.postForEntity(s, httpEntity, Object.class);
        MetaObject MetaObject= SystemMetaObject.forObject(objectResponseEntity.getBody());
        getAttributeList((String) MetaObject.getValue("data.access_token"));
    }


    synchronized void  getAttributeList(String access_token) throws Exception {
        Date date = LocalDateUtils.addDateDays(new Date(), -10);
        String start = LocalDateUtils.format(date, LocalDateUtils.DATE_PATTERN);
        String end = LocalDateUtils.format(new Date(), LocalDateUtils.DATE_PATTERN);
        RestTemplate REST_TEMPLATE = new RestTemplate();
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("timestamp", System.currentTimeMillis() / 1000 + "");
        queryParam.put("access_token", access_token);
        queryParam.put("app_key", appId);
        queryParam.put("offset", 0);
        queryParam.put("length", 100);
        queryParam.put("search_field_time", "creator_time");//入库时间
        queryParam.put("start_date",start);
        queryParam.put("end_date", end);
//        List<String> pans=new ArrayList();
//        pans.add("PP2308021194");
//        queryParam.put("plan_sns", pans);
        List statuss=new ArrayList();
        statuss.add(2);
        queryParam.put("status",statuss);//获取待采购的单子 PP2308021194
        String sign = ApiSign.sign(queryParam, appId);
        queryParam.put("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(queryParam, requestHeaders);
        String s = populateQueryParams(queryParam, addrssInfo.path+addrssInfo.getPurchasePlans,false);
        String s2 = REST_TEMPLATE.postForObject(s, requestEntity, String.class);
        lingXingPurchasePlans lingXingPurchasePlans = JSON.parseObject(s2, lingXingPurchasePlans.class);
        Assert.isTrue(lingXingPurchasePlans.getCode().intValue()!=3001002,"ip没在白名单");
        if (lingXingPurchasePlans.getData().size()>0){
            Map<String, List<lingXingPurchasePlans.DataDTO>> collect = lingXingPurchasePlans.getData().stream().collect(Collectors.groupingBy(com.fowo.api.service.handleWork.jindieEntity.lingXingPurchasePlans.DataDTO::getPpgSn));
            for(String key:collect.keySet()){
                List<lingXingPurchasePlans.DataDTO> dataDTOS = collect.get(key);
                PurchasePlansVo model=new PurchasePlansVo();
                List<PurchasePlansProductItemVo> procurementPlan=new ArrayList<>();
                PurchasePlans one5 = purchasePlansService.getOne(Wrappers.<PurchasePlans>query()
                        .lambda().eq(PurchasePlans::getPpgSn, key));
                if(one5!=null){
                    continue;
                }
                lingXingPurchasePlans.DataDTO dataDTO2 = dataDTOS.get(0);
                model.setStatus("2");
                model.setCreateTime(LocalDateUtils.toDate(dataDTO2.getCreateTime(),LocalDateUtils.DATE_TIME_PATTERN));
                model.setCreateName2(dataDTO2.getCreatorRealName());
                //设置主表参数
                model.setPpgSn(key);
                for(int i=0;i<dataDTOS.size();i++){
                    lingXingPurchasePlans.DataDTO dataDTO = dataDTOS.get(i);
                    PurchasePlansProductItemVo purchasePlansProductItemVo=new PurchasePlansProductItemVo();
                    purchasePlansProductItemVo.setPlanSn(dataDTO.getPlanSn());
                    PurchasePlansProduct one4 = purchasePlansProductService.getOne(Wrappers.
                            <PurchasePlansProduct>query().lambda().eq(PurchasePlansProduct::getPlanSn, dataDTO.getPlanSn()));
                    if(one4!=null){
                        purchasePlansProductItemVo.setParentPurchasePlans(one4.getParentPurchasePlans());
                        purchasePlansProductItemVo.setId(one4.getId());
                    }
                    //设置主表备注
                    model.setRemark(dataDTO.getPlanRemark());

                    purchasePlansProductItemVo.setStatus(dataDTO.getStatus().toString());
                    if(dataDTO.getSid()!=null&&dataDTO.getSid().intValue()!=0){
                        ShopInfo one = shopInfoService.getOne(Wrappers.<ShopInfo>query().lambda().eq(ShopInfo::getShopCode, dataDTO.getSid()));
                        Assert.notNull(one, dataDTO.getSid()+"店铺在供应链系统没找到");
                        purchasePlansProductItemVo.setSid(one!=null?one.getId():null);
                        if(dataDTO.getFnsku()!=null){
                            List<ListingFather> list = listingFatherService.list(Wrappers.<ListingFather>query().lambda().eq(ListingFather::getFnsku, dataDTO.getFnsku()));
                            Assert.isTrue(list.size()>0,dataDTO.getFnsku()+"fnsku在供应链系统不存在");
                            purchasePlansProductItemVo.setFnsku(list.get(0).getId());
                        }
                    }
                    Product one1 = service.getOne(Wrappers.<Product>query().lambda().eq(Product::getSku, "ER020528-R-15MM"));
                    purchasePlansProductItemVo.setProduct(one1!=null?one1.getId():null);
                    purchasePlansProductItemVo.setFnskuName(dataDTO.getFnsku());
                    Assert.notNull(one1, dataDTO.getSku()+"产品在供应链系统没找到");
                    purchasePlansProductItemVo.setPicUrl(one1!=null?one1.getPicUrl():null);
                    purchasePlansProductItemVo.setPsqMod(dataDTO.getQuantityPlan());
                    purchasePlansProductItemVo.setQuantityPlan(dataDTO.getQuantityPlan());//quantityPlan
                    purchasePlansProductItemVo.setSku(dataDTO.getSku());//marketplace
                    purchasePlansProductItemVo.setMarketplace(dataDTO.getMarketplace());
                    purchasePlansProductItemVo.setMsku(dataDTO.getMsku().size()>0?dataDTO.getMsku().toString():null);
                    String localInventory = purchaseOrderService.getLocalInventory(purchasePlansProductItemVo.getSid(), purchasePlansProductItemVo.getProduct(), purchasePlansProductItemVo.getFnsku());
                    String fbaInventory = purchaseOrderService.getFbaInventory(purchasePlansProductItemVo.getSid(), purchasePlansProductItemVo.getProduct(), dataDTO.getFnsku());
                    String skuSales = purchaseOrderService.getSale(purchasePlansProductItemVo.getSid(), purchasePlansProductItemVo.getProduct(), purchasePlansProductItemVo.getFnsku());
                    purchasePlansProductItemVo.setLocalDayList(localInventory);
                    purchasePlansProductItemVo.setFbaDayList(fbaInventory);
                    purchasePlansProductItemVo.setSkuSales(skuSales);

                    if(StringUtils.isNotBlank(dataDTO.getCgOptUsername())){
                        SysUser one = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getName, dataDTO.getCgOptUsername()));
                        Assert.notNull(one, dataDTO.getCgOptUsername()+"采购员在供应链系统没找到");
                        purchasePlansProductItemVo.setCgUid(one.getId());
                        purchasePlansProductItemVo.setCgOptUsername(dataDTO.getCgOptUsername());
                    }

                    purchasePlansProductItemVo.setRemark(dataDTO.getRemark());
                    if(StringUtils.isNotBlank(dataDTO.getSupplierName())){
                        Supplier one2 = supplierServiceImpl.getOne(Wrappers.<Supplier>query().lambda().eq(Supplier::getSupplierName, dataDTO.getSupplierName()));
                        Assert.notNull(one2, dataDTO.getSupplierName()+"供应商在供应链系统没找到");
                        purchasePlansProductItemVo.setSupplierId(one2!=null?one2.getId():null);
                    }
                    //判断不为空
                    if(StringUtils.isNotBlank(dataDTO.getWarehouseName())){
                        Warehouse one3 = warehouseService.getOne(Wrappers.<Warehouse>query().lambda().eq(Warehouse::getName, dataDTO.getWarehouseName()));
                        Assert.notNull(one3, dataDTO.getWarehouseName()+"仓库在供应链系统没找到");
                        purchasePlansProductItemVo.setWid(one3!=null?one3.getId():null);
                    }
                    purchasePlansProductItemVo.setCgBoxPcs(dataDTO.getCgBoxPcs());
                    procurementPlan.add(purchasePlansProductItemVo);
                }
                model.setProcurementPlan(procurementPlan);
                if(model.getId()!=null){
                    List<PurchasePlansProduct> list = purchasePlansProductService.list(Wrappers.<PurchasePlansProduct>query()
                            .lambda().eq(PurchasePlansProduct::getParentPurchasePlans, model.getId())
                            .isNotNull(PurchasePlansProduct::getQuantityPurchased));
                    if(model.getStatus()!="2"&&list.size()==0){
                      //quantityPurchased
                        purchasePlansService.update(model);
                    }
                }else{
                    purchasePlansService.create(model);
                }
            }
        }
    }


    static String populateQueryParams(Map<String, Object> request,String purl,boolean isEncode) {
        if(request.isEmpty()){
            return purl;
        }
        StringBuilder url = new StringBuilder(purl);
        url.append("?");
        for (Map.Entry<String, Object> entry : request.entrySet()) {
            try {
                if(isEncode){
                    url.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
                }else
                {
                    url.append(entry.getKey()).append("=").append(entry.getValue());
                }
                url.append("&");
            } catch (UnsupportedEncodingException e) {
            }
        }
        if (url.charAt(url.length() - 1) == '&') {
            url.deleteCharAt(url.length() - 1);
        }
        return url.toString();
    }


}
